//
//  EmptyStyleTableView.m
//  YanXiuWang
//
//  Created by 慧趣小歪 on 17/2/10.
//  Copyright © 2017年 小分队. All rights reserved.
//

#import "EmptyStyleView.h"
#import <objc/runtime.h>


@implementation UIView (EmptyView)

- (__kindof UIView *)emptyView {
    return objc_getAssociatedObject(self, "view_emptyView");
}

- (void)setEmptyView:(__kindof UIView *)emptyView {
    objc_setAssociatedObject(self, "view_emptyView", emptyView, OBJC_ASSOCIATION_ASSIGN);
    if (emptyView.superview != self) {
        CGSize size = self.bounds.size;
        [self addSubview:emptyView];
        CGFloat y = self.isEmptyMarginTop ? CGRectGetHeight(emptyView.frame) / 2 : size.height / 2;
        emptyView.center = CGPointMake(size.width / 2, y);
        emptyView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    }
}

- (BOOL)isEmptyMarginTop {
    NSNumber *isMarginTop = objc_getAssociatedObject(self, "isEmptyMarginTop");
    return isMarginTop.boolValue;
}

- (void)setIsEmptyMarginTop:(BOOL)isEmptyMarginTop {
    objc_setAssociatedObject(self, "isEmptyMarginTop", @(isEmptyMarginTop), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)isEmpty {
    return !self.emptyView.hidden && self.emptyView.superview != nil;
}

- (void)setIsEmpty:(BOOL)isEmpty {
    UIView *emptyView = self.emptyView;
    
    if (emptyView == nil) return;
    
    emptyView.hidden = !isEmpty;
    
    if (!emptyView.hidden && emptyView.superview == nil) {
        [self addSubview:emptyView];
        emptyView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    }
    CGSize size = self.bounds.size;
    CGFloat y = self.isEmptyMarginTop ? CGRectGetHeight(emptyView.frame) / 2 : size.height / 2;
    emptyView.center = CGPointMake(size.width / 2, y);
}

@end

@implementation EmptyStyleTableView

- (void)awakeFromNib {
    [super awakeFromNib];
    if (_emptyView.superview == nil) {
        _emptyView.hidden = YES;
        [self addSubview:_emptyView];
    }
}


@end

@implementation EmptyStyleCollectionView

- (void)awakeFromNib {
    [super awakeFromNib];
    if (_emptyView.superview == nil) {
        _emptyView.hidden = YES;
        [self addSubview:_emptyView];
    }
}

@end

@implementation EmptyStyleUIView

- (void)awakeFromNib {
    [super awakeFromNib];
    if (_emptyView.superview == nil) {
        _emptyView.hidden = YES;
        [self addSubview:_emptyView];
    }
}

@end
